package main

import (
	"errors"
	"log"
	"net"
	"net/rpc"
)

type UserInfo struct {
	Id    string `json:"id"`
	Name  string `json:"name"`
	Phone string `json:"phone"`
}

var userMap = map[string]UserInfo{
	"1": {
		Id:    "1",
		Name:  "test1",
		Phone: "16431346345",
	},
	"2": {
		Id:    "2",
		Name:  "test2",
		Phone: "134546431312",
	},
	"3": {
		Id:    "3",
		Name:  "test3",
		Phone: "5497465354652",
	},
}

type (
	Req struct {
		Id string
	}

	Resp struct {
		Id    string
		Name  string
		Phone string
	}
)

type UserService struct{}

func (u *UserService) GetUserInfo(req Req, resp *Resp) error {
	if u, ok := userMap[req.Id]; ok {
		resp.Id = u.Id
		resp.Name = u.Name
		resp.Phone = u.Phone
		return nil
	}
	return errors.New("用户不存在")
}

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal("监听8080端口失败", err)
	}
	defer listener.Close()
	rpc.Register(new(UserService))
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Fatal("接受连接失败", err)
		}
		go func() {
			defer conn.Close()
			rpc.ServeConn(conn)
		}()
	}

}
